package com.artup.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.dao.AddressDao;
import com.artup.dao.InvoiceDao;
import com.artup.dao.OrderDao;
import com.artup.dao.PaymentDao;
import com.artup.dao.WorksDao;
import com.artup.pojo.Address;
import com.artup.pojo.Invoice;
import com.artup.pojo.Order;
import com.artup.pojo.Payment;
import com.artup.pojo.Region;
import com.artup.pojo.Works;
import com.artup.service.MesService;
import com.artup.util.CommonUtils;
import com.artup.util.cache.RedisUtils;
import com.artup.util.file.PropertiesUtils;
import com.artup.util.http.HttpClientUtil;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

/**
 * MES
 * @author hapday
 * @date 2017年8月9日 @Time 下午3:25:02
 */
@Slf4j
@Service( value = "mesService" )
public class MesServiceImpl implements MesService {
	private static Jedis jedis = RedisUtils.getJedis();
	
	@Autowired
	private OrderDao orderDao;

	@Autowired
	private PaymentDao paymentDao;

	@Autowired
	private AddressDao addressDao;

	@Autowired
	private InvoiceDao invoiceDao;

	@Autowired
	private WorksDao worksDao;

	@Autowired
	private HttpClientUtil httpClientUtil;

	@Override
	@Async
	public void noticeMesOrder(String orderCode) {
		log.info("开始通知 MES 系统，orderCode = {}", orderCode);
		
		if(StringUtils.isBlank(orderCode)) {
			log.warn("无订单号！");
			
			return;
		}
		
		Order order = null;
		try {
			order = this.orderDao.selectOrderByCode(orderCode);
		} catch (SQLException e) {
			log.error("根据【编号】查询【订单详情】 - 失败！", e);
		}
		
		if(null == order) {
			log.warn("未找到的订单！");
			
			return;
		}
		
		Address address = null;
		try {
			address = this.addressDao.selectAddressById(order.getAddressId());
		} catch (SQLException e) {
			log.error("根据【ID】查询【地址】 - 失败！", e);
		}
		
		Invoice invoice = null;
		try {
			invoice = this.invoiceDao.selectInvoiceById(order.getInvoiceId());
		} catch (SQLException e) {
			log.error("根据【ID】查询【发票详情】 - 失败！ ", e);
		}
		
		Payment payment = null;
		try {
			payment = this.paymentDao.selectPaymentByOrderCode(orderCode);
		} catch (SQLException e) {
			log.error("根据【订单号】查询【支付流水】 - 失败！", e);
		}
		
		List<Works> worksList = null;
		try {
			worksList = this.worksDao.selectWorksListByOrderCode(orderCode);
		} catch (SQLException e) {
			log.error("根据【订单号】查询【作品列表】 - 失败！", e);
		}
		
		String url = PropertiesUtils.getValue("mes.url") + "serve/saveOrderInfo";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("order_id", orderCode);	// 订单号
		
		if(null != address) {
			parameterMap.put("buy_name", address.getName());	// 收货人姓名
			parameterMap.put("buy_tel", address.getMobileCode());		// 收货人手机号
			parameterMap.put("buy_address", address.getDetail());		// 收货人详细地址
			
			String regions = jedis.get(Constants.CACHE_TYPE_REGION_LIST);
			/*String regions = null;
			List<String> regionList_ = jedis.mget(Constants.CACHE_TYPE_REGION_LIST);
			if(null != regionList_) {
				regions = regionList_.get(0);
			}*/
			
			if(CommonUtils.isNotEmpty(regions)) {
				List<Region> regionList = JSONArray.parseArray(regions, Region.class);
				
				for(Region region : regionList) {
					if(address.getProvinceId() == region.getId()){
						parameterMap.put("buy_province", region.getName());	// 收货人省份
					}
					if(address.getCityId() == region.getId()){
						parameterMap.put("buy_city", region.getName());	// 收货人地市
					}
					if(address.getDistrictId() == region.getId()){
						parameterMap.put("buy_county", region.getName());	// 收货人区县
					}
				}
			}
			
		}
		
		parameterMap.put("buy_email", orderCode);	// 收货人邮箱
		parameterMap.put("shipping_total", order.getExpressFee());	// 快递费
		parameterMap.put("shipping_name", "顺丰");	// 物流名称
		parameterMap.put("item_count", order.getTotalQuantity());		// 商品总数量
		parameterMap.put("item_total", orderCode);	// 商品总价格
		parameterMap.put("total", order.getTotalPrice());	// 订单总金额
		
		if(null != payment) {
			parameterMap.put("pay_total", payment.getTotalPrice());	// 订单实际支付的总金额
		}
		
		parameterMap.put("order_created", CommonUtils.dateTimeFormat(order.getCreateTime()));	// 订单创建时间
		if(null == invoice) {
			parameterMap.put("ifinvoice", 1);	// 是否需要发票
		} else {
			parameterMap.put("ifinvoice", 0);	// 是否需要发票
		}
		parameterMap.put("source", "ios");	// 订单来源
		
		if(CommonUtils.isNotEmpty(worksList)) {
			List<Map<String, Object>> worksList_ = new ArrayList<Map<String, Object>>();
			
			for(Works works : worksList) {
				if(null == works) {
					continue;
				}
				
				Map<String, Object> worksMap = new HashMap<String, Object>();
				worksMap.put("goods_name", works.getName());
				worksMap.put("goods_price", works.getPrice());
				worksMap.put("amount", works.getQuantity());
				worksMap.put("goods_img_url", works.getThumbnailPath());
				worksMap.put("product_code", works.getSkuCode());
				
				worksList_.add(worksMap);
			}

			parameterMap.put("goods", worksList_);	// 作品列表
		}
		
		List<NameValuePair> requestParametes = new ArrayList<NameValuePair>();  
        requestParametes.add(new BasicNameValuePair("data", JSONObject.toJSONString(parameterMap)));
        Object result = this.httpClientUtil.post(url, requestParametes, Object.class);
		log.info("result = {}", result);
		log.info("通知 MES 系统结束。");
	}

}
